from time import sleep
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from utils.log_util import logger
from utils.webdriver_util import screenshot, input_text, click_button
project_address = "https://casdev.haid.com.cn/cas/login?service=http%3A%2F%2Ffin-uat.haid.com.cn%2Fjpaas%2Fuser%2FticketLogin"


# 配置 WebDriver 夹具
@pytest.fixture(scope="module")
def driver():
    # 设置浏览器
    options = webdriver.ChromeOptions()
    # 无头模式 CI/CD中使用
    # options.add_argument("--headless")
    # options.add_argument("--disable-gpu")
    options.add_argument("--disable-extensions")
    # 启动浏览器
    logger.info("开始启动chrome浏览器")
    driver = webdriver.Chrome(options=options)
    driver.maximize_window()  # 窗口最大化

    # 在测试结束后，关闭浏览器
    yield driver
    logger.info('测试结束，关闭浏览器')
    driver.quit()


@pytest.fixture(scope="module")
def get_login_status(driver,request):
    """
    作用域：模块   自动执行
    """
    username,password = request.param
    driver.get(project_address)
    input_text(driver, By.XPATH,
               '//input[@id="username"]', username)
    input_text(driver, By.XPATH,
               '//input[@id="password"]', password)
    click_button(driver, By.XPATH,
                 '//input[@value="登录"]')
    sleep(3)


# # 指定用户登录
# @pytest.fixture()
# def specify_user_login(driver):
#     driver.get(project_address)
#
#     # 通过外部参数传递用户名和密码
#     def _login(username, password):
#         input_text(driver, By.XPATH, '//*[@id="app"]/div/div/form/div[1]/div/div/input', username)
#         input_text(driver, By.XPATH, '//*[@id="app"]/div/div/form/div[2]/div/div/input', password)
#         click_button(driver, By.XPATH, '//*[@id="app"]/div/div/form/div[3]/div/button/span')
#
#     return _login


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """ 捕获测试报告并记录日志，失败时截图 """
    outcome = yield
    report = outcome.get_result()

    # 仅在测试执行阶段（'call'）时处理结果
    if report.when == "call":
        o = report.outcome  # 获取测试结果
        s = f"用例执行结果: [{o}]"
        # 通过测试项的 funcargs 获取 driver
        driver = item.funcargs.get('driver')
        screenshot(driver)
        if o == "failed":
            logger.error(s)
        elif o == "skip":
            logger.warning(s)
        else:
            logger.info(s)
